﻿@model EmailMaker.Controllers.ViewModels.EmailEditRecipientsModel
@using EmailMaker.Controllers;
@using EmailMaker.Website.Extensions

@{
    ViewBag.Title = "EmailEditRecipients";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
    var editRecipientsModel;

    $(document).ready(function () {
        var fromAddresses = _.map(@Html.Raw(Html.ToJson(Model.FromAddresses)), function(address) { return htmlEncode(address); });
        var toAddresses = @Html.Raw(Html.ToJson(Model.ToAddresses));
        var toAddressesString = toAddresses.join(", ");
        editRecipientsModel = {
            fromAddresses: fromAddresses,
            selectedFromAddress: ko.observable(),
            toAddresses: ko.observable(toAddresses),
            toAddressesString: ko.observable(toAddressesString),
            sendEmail: function() {
                $.postJson("@(Html.BuildUrlFromExpressionWithoutParameters<EmailController>(c => c.EnqueueEmailToBeSent(null)))", {
                    EmailId: @(Model.EmailId),
                    FromAddress: editRecipientsModel.selectedFromAddress(),
                    Recipients: editRecipientsModel.toAddressesString()
                }, function() {
                    reloadIframe("templateHtml");
                });
            }
        };

        ko.applyBindings(editRecipientsModel, document.getElementById("editRecipients"));
    });
</script>

<h2>Edit recipients</h2>

<div id="editRecipients">
    <table>
        <tr>
            <td>From:</td>
            <td><select data-bind="options: fromAddresses, value: selectedFromAddress"></select></td>
        </tr>
        <tr>
            <td>To:</td>
            <td><textarea data-bind="value: toAddressesString"></textarea></td>            
        </tr>
    </table>
    <button data-bind="click: sendEmail">Send email</button>
</div>
<iframe id="emailHtml" src="@(Html.BuildUrlFromExpressionWithoutParameters<EmailController>(c => c.GetHtml(default(int))))/@(Model.EmailId)" width="900" height="800">
</iframe>
